import axios from 'axios'
import store from '../store'
import { MessageBox } from 'mint-ui'
import { Indicator } from 'mint-ui'
import { Const } from '@/consts'
import utils from '@/utils'
import Qs from 'qs'
import bus from '@/bus'

let requestQ = []
const device = 'wechat|' + navigator.userAgent

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API_URL, // api的base_url
  // baseURL: '', // api的base_url
  timeout: 30000, // 请求超时时间
  // `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [
    function (data, headers) {
      headers[Const.H_DEVICE] = device
      headers[Const.H_AUTH] = utils.getUserToken()

      if (headers['Content-Type']) {
        return data
      }


      return Qs.stringify(data)
    }
  ]
})

// request 拦截器
service.interceptors.request.use((config) => {
  if (!config.headers.NLoading) {
    requestQ.push(1)
    Indicator.open()
  } else {
    delete config.headers.NLoading
  }

  return config
}, (error) => {
  // error
})

// respone 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    // const res = response.data
    // if (res.code !== 200) {
    //   // Message({
    //   //   message: res.message,
    //   //   type: 'error',
    //   //   duration: 5 * 1000
    //   // })

    //   // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
    //   if (res.code === 508 || res.code === 512 || res.code === 514) {
    //     MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
    //       confirmButtonText: '重新登录',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('FedLogOut').then(() => {
    //         location.reload()// 为了重新实例化vue-router对象 避免bug
    //       })
    //     })
    //   }
    //   return Promise.reject('error')
    // } else {
    //   return response.data
    // }

    if (!requestQ.pop() || !requestQ.length) {
      Indicator.close()
    }

    let resp = response.data
    resp.statusCode = resp.statusCode || '200'
    if (resp[Const.RESP_STATUS] == Const.STATUS_OK) {
      return resp
    } else if (resp[Const.RESP_STATUS] == Const.STATUS_EXPIRE) {
      bus.$emit('loginExpired')
      return Promise.reject(resp)
    } else {
      return Promise.reject(resp)
    }
  },
  error => {
    // console.log('err' + error) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })

    if (!requestQ.pop() || !requestQ.length) {
      Indicator.close()
    }

    let resp = error.response.data || {}
    if (resp[Const.RESP_STATUS] == Const.STATUS_EXPIRE) {
      bus.$emit('loginExpired')
    }

    return Promise.reject(resp)
  }
)

export default service
